package com.wn.fileuporload;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

@Controller
public class fileDownload {
    /*
   通过文件名进行下载，路径参考上传路径
   后期开发，路径参考url地址(比如使用了云服务)，或者是参考数据库中存储的路径位置
   */
    @RequestMapping("/download")
    public ResponseEntity<byte[]> downLoad(HttpServletRequest request,
                                           @RequestParam("filename") String filename,
                                           Model model) throws UnsupportedEncodingException {
        //获取下载文件路径
        String path = request.getServletContext().getRealPath("/images/");
        File file = new File(path + File.separator + filename);
        HttpHeaders httpHeaders = new HttpHeaders();
        //下载显示的文件名,解决中文名称乱码的问题
        String downloadFilename = new String(filename.getBytes("UTF-8"), "ISO-8859-1");
        //通知浏览器以attachment(下载方式)打开图片
        httpHeaders.setContentDispositionFormData("attachment",downloadFilename);
        //application/octet-stream:二进制流数据(最常见的文件下载)
        httpHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        try {
            //文件转换为字节数组
            return  new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),httpHeaders, HttpStatus.OK);
        } catch (IOException e) {
            HttpHeaders httpHeader1 = new HttpHeaders();
            httpHeader1.setContentType(MediaType.APPLICATION_JSON);
            return new ResponseEntity("文件名错误!",httpHeader1,HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
}
